<?php
use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Autoloader;
use PHPSocketIO\SocketIO;
use Workerman\Lib\Timer;

// composer autoload
require_once __DIR__ . '/vendor/autoload.php';
Worker::$logFile = '/tmp/workerman.log';

//$io = new SocketIO(2021);
//// 当有客户端连接时
//$io->on('connection', function ($connection) use ($io) {
//    error_log('connection-' . date('Y-m-d H:i:s') . PHP_EOL, 3, __DIR__ . '/socket.log');
//    // 定义chat message事件回调函数
//    $connection->on('msg', function ($msg) use ($io) {
//        error_log(var_export($msg, true) . PHP_EOL, 3, __DIR__ . '/socket.log');
//        // 触发所有客户端定义的chat message from server事件
//        for ($i = 0; $i < 20; $i++) {
//            $io->emit('msg', $i);
//        }
//    });
//});


$worker = new Worker('websocket://0.0.0.0:2021');
//$worker->count = 4;
$worker->onWorkerStart = function ($worker) {
    echo "Worker starting...\n";
    // 定时，每10秒一次
    Timer::add(10, function () use ($worker) {
        // 遍历当前进程所有的客户端连接，发送当前服务器的时间
        foreach ($worker->connections as $connection) {
            $data = ['time' => time(), 'msg' => 'ok'];
            $connection->send(json_encode($data));
        }
    });
};
$worker->onMessage = function ($connection, $data) {

    error_log(date('Y-m-d H:i:s').'=>connection:' . var_export($connection, true) . PHP_EOL, 3, __DIR__ . '/socket.log');
    error_log(date('Y-m-d H:i:s') . '=>receive:' . var_export($data, true) . PHP_EOL, 3, __DIR__ . '/socket.log');
    $connection->send('服务器响应数据：'.$data);
};
$worker->onClose = function ($connection) {
    echo "connection closed\n";
};


if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
